package com.qhit.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public @ResponseBody Map login(String username, String password){
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(username);
        token.setPassword(password.toCharArray());
        Subject subject = SecurityUtils.getSubject();
        HashMap m = new HashMap();
        try {
            subject.login(token);
            //UnknownAccountException 用户异常
        }catch (UnknownAccountException e){
            m.put("msg","账户未注册！！");
             return m;
            //IncorrectCredentialsException  密码异常
        }catch (IncorrectCredentialsException e){
            m.put("msg","密码错误！！");
           return m;
            //AuthenticationException 认证异常
        }catch (AuthenticationException e){
            m.put("msg","认证失败！！");
            return m;
        }
        if (subject.isAuthenticated()){
            m.put("msg","登陆成功！！");

        }else {
            m.put("msg","登陆失败！！");

        }
        return m;
    }
}
